package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.dao.BookMapper;
import com.example.demo.dao.ChapterMapper;
import com.example.demo.dao.HistoryMapper;
import com.example.demo.model.Book;

import com.example.demo.model.Chapter;
import com.example.demo.model.History;
import com.example.demo.model.User;
import com.example.demo.service.UserFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述：
 *
 * @Author: Zhanghf
 * @Date: 2021/5/30 11:13
 */
@Controller
public class HistoryController {
    @Autowired(required = false)
    private BookMapper bookMapper;
    @Autowired(required = false)
private ChapterMapper chapterMapper;
    @Autowired(required = false)
    private HistoryMapper historyMapper;
    @Autowired(required = false)
private UserFeignService userFeignService;

@GetMapping("personhistory")
    public String history(HttpServletResponse response, HttpServletRequest request, Model model, HttpSession session)
    {
        User user = (User) session.getAttribute("user");
        model.addAttribute("user",user);
        List<History> historys = historyMapper.selectList(new QueryWrapper<History>().eq("userid", user.getId()));
        List<Chapter> chapters=new ArrayList<>();
        ArrayList<Book> books = new ArrayList<>();
        for (History history : historys) {
            Book book = bookMapper.selectOne(new QueryWrapper<Book>().eq("id", history.getBookid()));
            books.add(book);
            Chapter chapter = chapterMapper.selectOne(new QueryWrapper<Chapter>().eq("bookid", history.getBookid()).eq("chapterid", history.getChapterid()));
            chapters.add(chapter);
        }
        model.addAttribute("historys",historys);
        model.addAttribute("books",books);
        model.addAttribute("chapters",chapters);
        model.addAttribute("userid",user.getId());
        return "history";
    }
    @PostMapping("historydelete")
    public String historydelete(HttpServletResponse response, HttpServletRequest request, Model model, HttpSession session)
    {

        String bookid = request.getParameter("bookid");
        String userid = request.getParameter("userid");
        String chapterid = request.getParameter("chapterid");

        userFeignService.deletehistory(Integer.parseInt(bookid),Integer.parseInt(chapterid),Integer.parseInt(userid));

        return "forward:personhistory";
    }
}
